//
//  Global.m
//  basic
//
//  Created by Jack on 2016/12/12.
//  Copyright © 2016年 Jack. All rights reserved.
//

#import "Global.h"
#import "UWOHttpService.h"
#import "NSString+extend.h"

#import "DLAVAlertView.h"

//static NSString *kAPP_URL = @"http://itunes.apple.com/lookup?id=";
static NSString *kAPP_Id = @"1055273038";

@implementation Global

+ (id)sharedGlobal
{
    static Global *sharedInstance = nil;
    static dispatch_once_t onceTokens;
    dispatch_once(&onceTokens, ^{
        sharedInstance = [[Global alloc] init];
    });
    
    return sharedInstance;
}

#pragma mark - checkUpdateApp
- (void)checkUpdateApp
{
    
    NSString *urlStr = [NSString stringWithFormat:@"http://itunes.apple.com/lookup?id=%@", kAPP_Id];
    
    WEAKSELF
    [UWOHttpService POST:urlStr parameters:nil success:^(NSURLSessionDataTask *task, id response) {
        
        if (response && [response isKindOfClass:[NSDictionary class]]) {
            
            NSDictionary *appInfoDict = (NSDictionary*)response;
            NSArray *resultArray = [appInfoDict objectForKey:@"results"];
            
            if (![resultArray count]) {
                DLog(@"error : resultArray == nil");
                return;
            }
            
            NSDictionary *infoDict = [resultArray objectAtIndex:0];
            //获取服务器上应用的最新版本号
            NSString *newVewsion1 = infoDict[@"version"];
            NSString *newVewsion = [newVewsion1 stringByReplacingOccurrencesOfString:@"." withString:@""];
            newVewsion = [weakSelf getFullVersionNum:newVewsion];
            NSUInteger updateVersion = [newVewsion integerValue];
            
            _trackViewUrl = infoDict[@"trackViewUrl"];
            
            //获取当前设备中应用的版本号
            NSDictionary *oldInfoDic = [[NSBundle mainBundle] infoDictionary];
            NSString *oldVersion = [oldInfoDic objectForKey:@"CFBundleShortVersionString"];
            oldVersion = [oldVersion stringByReplacingOccurrencesOfString:@"." withString:@""];
            oldVersion = [weakSelf getFullVersionNum:oldVersion];
            NSUInteger currentVersion = [oldVersion integerValue];
            
            //判断两个版本是否相同
            if (currentVersion < updateVersion) {
                NSString *titleStr = [NSString stringWithFormat:@"发现新版本(%@)", newVewsion1];
                NSString *messageStr = [NSString stringWithFormat:@"%@", infoDict[@"releaseNotes"]];
                
                DLAVAlertView *alertView = [[DLAVAlertView alloc] initWithTitle:titleStr message:nil delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"更新", nil];
                
                CGSize contentSize = [NSString calculateTextHeight:[UIFont systemFontOfSize:14] givenText:messageStr givenWidth:250];
                
                UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 270, contentSize.height)];
                contentView.backgroundColor = [UIColor clearColor];
                
                UILabel *contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(10.0, 0.0, 250, contentSize.height)];
                contentLabel.text = messageStr;
                contentLabel.numberOfLines = 0;
                contentLabel.font = [UIFont systemFontOfSize:14];
                contentLabel.lineBreakMode = NSLineBreakByCharWrapping;
                [contentView addSubview:contentLabel];
                contentLabel.backgroundColor = [UIColor clearColor];
                
                alertView.contentView = contentView;
                [alertView showWithCompletion:^(DLAVAlertView *alertView, NSInteger buttonIndex) {
                    
                    DLog(@"Tapped button '%@' at index: %ld", [alertView buttonTitleAtIndex:buttonIndex], (long)buttonIndex);
                    
                    if (buttonIndex == 1) { //点击”升级“按钮，就从打开app store上应用的详情页面
                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.trackViewUrl]];
                    }
                    else {
                        if (buttonIndex == 0 && self.isForceUpdate) {
                            exit(0);
                        }
                    }
                    
                }];
                
            }
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [error setValue:@"网络连接失败" forKey:@"domain"];
        
    }];
}

- (NSString*)getFullVersionNum:(NSString*)versionStr {
    
    if ([NSString isNotEmpty:versionStr]) {
        
        if (versionStr.length < 5) {
            
            NSUInteger length = versionStr.length;
            
            for (int i = 0; i < 5-length; i++) {
                versionStr = [NSString stringWithFormat:@"%@0",versionStr];
            }
            
            return versionStr;
        }
        else {
            return versionStr;
        }
    }
    else {
        return @"00000";
    }
    
}

@end
